﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.ComponentModel;
using System.Reflection;

namespace TFSMailer.Classes
{

    public class Users 
    {
        public Users()
        {
        }


        /// <summary>
        /// Gets the users list.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public  void GetUsersList(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            if (worker != null)
            {
                worker.ReportProgress(0);
            }
            UserThreadArgs args = (UserThreadArgs)e.Argument;

            Dictionary<string, Identity> list = new Dictionary <string, Identity>();

            TeamProject tp = args.Sourcecontrol.GetTeamProject(args.TeamProject);
            IGroupSecurityService sec = (IGroupSecurityService)args.Tfs.GetService(typeof(IGroupSecurityService));

            Identity[] appGroups = sec.ListApplicationGroups(tp.ArtifactUri.AbsoluteUri);
            foreach (Identity group in appGroups)
            {
                Identity[] groupMembers = sec.ReadIdentities(SearchFactor.Sid, new[] { group.Sid }, QueryMembership.Expanded);
                foreach (Identity member in groupMembers)
                {
                    //Console.WriteLine(member.DisplayName);
                    if (member.Members != null)
                    {
                        foreach (string memberSid in member.Members)
                        {
                            Identity memberInfo = sec.ReadIdentity(SearchFactor.Sid, memberSid, QueryMembership.None);
                            if (!list.Contains(new KeyValuePair<string, Identity>(memberInfo.DisplayName, memberInfo)))
                            {
                                list.Add(memberInfo.DisplayName, memberInfo);
                            }
                        }
                    }
                }
            }
            if (worker != null)
            {
                worker.ReportProgress(1);
            }
            e.Result = list;
        }

        /// <summary>
        /// Gets the users in project role.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        //public  Dictionary<string, Identity> GetUsersInProjectRole(TeamFoundationServer tfs, VersionControlServer sourcecontrol, string teamProject, string roles)
        public void GetUsersInProjectRole(object sender, DoWorkEventArgs e)
        {

            BackgroundWorker worker = sender as BackgroundWorker;
            if (worker != null)
            {
                worker.ReportProgress(0);
            }
            UserThreadArgs args = (UserThreadArgs)e.Argument;

            Dictionary<string, Identity> list = new Dictionary<string, Identity>();

            TeamProject tp = args.Sourcecontrol.GetTeamProject(args.TeamProject);
            IGroupSecurityService sec = (IGroupSecurityService)args.Tfs.GetService(typeof(IGroupSecurityService));

            Identity[] appGroups = sec.ListApplicationGroups(tp.ArtifactUri.AbsoluteUri);
            foreach (Identity group in appGroups)
            {
                
                Identity[] groupMembers = sec.ReadIdentities(SearchFactor.Sid, new string[] { group.Sid }, QueryMembership.Expanded);
                foreach (Identity member in groupMembers)
                {

                    //Console.WriteLine(member.DisplayName);
                    if (args.Roles.Equals("") || args.Roles.Equals(member.DisplayName))
                    {
                        if (member.Members != null)
                        {
                            foreach (string memberSid in member.Members)
                            {
                                Identity memberInfo = sec.ReadIdentity(SearchFactor.Sid, memberSid, QueryMembership.None);
                                if (!list.Contains(new KeyValuePair<string, Identity>(memberInfo.DisplayName, memberInfo)))
                                {
                                    list.Add(memberInfo.DisplayName, memberInfo);
                                }
                            }
                        }
                    }
                }
            }
            if (worker != null)
            {
                worker.ReportProgress(1);
            }
            e.Result = list;
            //return list;
        }


        public void GetAllUsersInProjectRole(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            if (worker != null)
            {
                worker.ReportProgress(0);
            }

            UserThreadArgs args = (UserThreadArgs)e.Argument;
            
            Dictionary<string, Identity> list = new Dictionary<string, Identity>();
            foreach (TeamProject tp in Projects.GetAllTeamProjects(args.Sourcecontrol, false))
            {
                args.Sourcecontrol.GetTeamProject(tp.Name);
                

                IGroupSecurityService sec = (IGroupSecurityService)args.Tfs.GetService(typeof(IGroupSecurityService));

                Identity[] appGroups = sec.ListApplicationGroups(tp.ArtifactUri.AbsoluteUri);
                foreach (Identity group in appGroups)
                {
                    Identity[] groupMembers = sec.ReadIdentities(SearchFactor.Sid, new[] { group.Sid }, QueryMembership.Expanded);
                    foreach (Identity member in groupMembers)
                    {
                        //Console.WriteLine(member.DisplayName);
                        if (args.Roles.Equals("") || args.Roles.Equals(member.DisplayName))
                        {
                            if (member.Members != null)
                            {
                                foreach (string memberSid in member.Members)
                                {
                                    Identity memberInfo = sec.ReadIdentity(SearchFactor.Sid, memberSid, QueryMembership.None);
                                    if (!list.Contains(new KeyValuePair<string, Identity>(memberInfo.Sid, memberInfo)))
                                    {
                                        list.Add(memberInfo.Sid, memberInfo);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (worker != null)
            {
                worker.ReportProgress(1);
            }
            e.Result = list;
            //return list;
        }

        public static Dictionary<string, Identity> GetGroupsInProject(TeamFoundationServer tfs, VersionControlServer sourcecontrol, string teamProject)
        {
            if (String.IsNullOrEmpty(teamProject))
            {
                return null;
            }
            Dictionary<string, Identity> list = new Dictionary<string, Identity>();

            TeamProject tp = sourcecontrol.GetTeamProject(teamProject);
            IGroupSecurityService sec = (IGroupSecurityService)tfs.GetService(typeof(IGroupSecurityService));

            Identity[] appGroups = sec.ListApplicationGroups(tp.ArtifactUri.AbsoluteUri);
            foreach (Identity group in appGroups)
            {                
                if (!list.Contains(new KeyValuePair<string, Identity>(group.DisplayName, group)))
                {
                    list.Add(group.DisplayName, group);
                }
               
            }

            return list;
        }

        public static Identity GetUserInfo(TeamFoundationServer tfs,  string accountname)
        {
            //string tfsUri = "YOURTFSSERVER";
            //string tfsUser = "YOURTFSACCOUNT";
            //string tfsPassword = "YOURTFSPASSWORD";
            //string sid = String.Empty;

            //NetworkCredential nc = new NetworkCredential(tfsUser, tfsPassword);

            //TeamFoundationServer tfs = new TeamFoundationServer(tfsUri, nc);

            IGroupSecurityService gss = (IGroupSecurityService)tfs.GetService(typeof(IGroupSecurityService));

            Identity identity = gss.ReadIdentity(SearchFactor.AccountName, accountname, QueryMembership.None);

            if (identity != null)
            {
                return identity;
            }

            return null;
        }
    }
}
